package com.leyou.item.service;

import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.pojo.Category;
import com.leyou.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Author: taft
 * @Date: 2018-9-25 18:28
 */
@Service
public class CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public List<Category> queryListByParent(Long pid) {
        //category对象，查询数据库时使用
        Category category = new Category();
        //从redis中获取分类数据
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        //第一级分类，
        if (pid == 0) {
            List<Category> categories = null;
            String firstLevel = ops.get("firstLevel");
            //redis中获取的数据为空，从数据库中获取，并保存一份到redis中
            if (StringUtils.isBlank(firstLevel)) {
                category.setParentId(pid);
                categories = categoryMapper.select(category);
                ops.set("firstLevel", Objects.requireNonNull(JsonUtils.serialize(categories)));
                return categories;
            }
            //从redis中获取到数据
           categories = JsonUtils.parseList(firstLevel, Category.class);
            return categories;
        }
        //第二级分类
        List<Category> list = null;
        String secondLevel = ops.get("secondLevel"+pid);
        //从redis中获取的数据为空，则从数据库中获取，并保存一份到redis中
        if (StringUtils.isBlank(secondLevel)) {
            category.setParentId(pid);
            list = categoryMapper.select(category);
            for (Category category1 : list) {
                category.setParentId(category1.getId());
                category1.setList(categoryMapper.select(category));
            }
            ops.set("secondLevel"+pid, Objects.requireNonNull(JsonUtils.serialize(list)));
            return list;
        }
        //从redis中获取到了数据，直接返回
         list = JsonUtils.parseList(secondLevel, Category.class);
        return list;
    }

    public List<String> queryNamesByIds(List<Long> cids) {

        List<Category> categories = categoryMapper.selectByIdList(cids);

        List<String> names = new ArrayList<>();

        for (Category category : categories) {
            names.add(category.getName());
        }

        return names;
    }
}
